<?php

namespace application\vote\controller;

use application\home\controller\auth;
use application\vote\models\vote_option_model;

class index extends auth {

    /**
     * 	投票列表页
     */
    public function lists() {
        $search = array('siteid' => $this->siteid);
        $ret = db('vote_subject')->where($search)->order('subjectid desc')->newpage();
        $this->assign('page', $ret['page']);
        $this->assign('items', $ret['items']);
        $this->display('vote/vote_lists', 'home');
    }

    /**
     * 投票显示页
     */
    public function show() {
        $type = intval($_GET['type']); //调用方式ID
        $subjectid = abs(intval($_GET['subjectid']));
        //取出投票标题
        $subject_arr = db('vote_subject')->where(['subjectid' => $subjectid])->find();
        $siteid = $subject_arr['siteid'];
        //增加判断，防止模板调用不存在投票时js报错 wangtiecheng
        if (!is_array($subject_arr)) {
            if (isset($_GET['action']) && $_GET['action'] == 'js') {
                exit;
            } else {
                showmsg(L('vote_novote'), 'blank');
            }
        }
        //显示模版
        $template = $subject_arr['template'] ? $subject_arr['template'] : 'vote_tp';
        //获取投票选项
        $options = vote_option_model::get_options($subjectid);

        //新建一数组用来存新组合数据
        $total = 0;
        $vote_data = array();
        $vote_data['total'] = 0; //所有投票选项总数
        $vote_data['votes'] = 0; //投票人数
        //获取投票结果信息
        $infos = db('vote_data')->where(['subjectid' => $subjectid])->select();
        //循环每个会员的投票记录
        foreach ($infos as $subjectid_arr) {
            extract($subjectid_arr);
            $arr = string2array($data);
            foreach ($arr as $key => $values) {
                $vote_data[$key] += 1;
            }
            $total += array_sum($arr);
            $vote_data['votes'] ++;
        }
        $vote_data['total'] = $total;

        //取出投票时间，如果当前时间不在投票时间范围内，则选项变灰不可选
        if (date("Y-m-d", TIMESTAMP) > $subject_arr['todate'] || date("Y-m-d", TIMESTAMP) < $subject_arr['fromdate']) {
            $check_status = 'disabled';
            $display = 'display:none;';
        } else {
            $check_status = '';
        }
        //JS调用
        if ($_GET['action'] == 'js') {
            if (!function_exists('ob_gzhandler'))
                ob_clean();
            ob_start();
            //$template = 'submit';
            $template = $subject_arr['template'];
            //根据TYPE值，判断调用模版
            switch ($type) {
                case 3://首页、栏目页调用
                    $true_template = 'vote_tp_3';
                    break;
                case 2://内容页调用
                    $true_template = 'vote_tp_2';
                    break;
                default:
                    $true_template = $template;
            }
            include template($true_template, 'vote');
            $data = ob_get_contents();
            ob_clean();
            exit(format_js($data));
        }

        $vote_options = array();
        foreach ($options as $option) {
            if ($vote_data['total'] == 0) {
                $option['per'] = 0;
            } else {
                $option['per'] = intval($vote_data[$option['optionid']] / $vote_data['total'] * 100);
            }
            $option['num'] = $vote_data[$option['optionid']] == '' ? '0' : $vote_data[$option['optionid']];
            $vote_options[] = $option;
        }
        $this->assign('vote_subject', $subject_arr);
        $this->assign('vote_data', $vote_data);
        $this->assign('vote_options', $vote_options);
        $this->assign('check_status', $check_status);
        $this->assign('display', $display);
        //前台投票列表调用默认页面,以免页面样式错乱.
        if ($_GET['show_type'] == 1) {
            $this->display('vote/vote_tp', 'home');
        } else {
            $this->display('vote/' . $template, 'home');
        }
    }

    /**
     * 处理投票
     */
    public function post() {
        $subjectid = intval($_POST['subjectid']);
        $siteid = $this->siteid;
        //判断是否已投过票,或者尚未到第二次投票期
        $return = $this->check($subjectid);
        switch ($return) {
            case 0:
                showmsg(L('vote_voteyes'), "/vote/index/result/?subjectid=$subjectid&siteid=$siteid");
                break;
            case -1:
                showmsg(L('vote_voteyes'), "/vote/index/result/?subjectid=$subjectid&siteid=$siteid");
                break;
        }
        if (!is_array($_POST['radio']))
            showmsg(L('vote_nooption'), 'blank');
        $time = TIMESTAMP;

        $data_arr = array();
        foreach ($_POST['radio'] as $radio) {
            $radio = intval($radio);
            $data_arr[$radio] = '1';
        }
        $new_data = array2string($data_arr); //转成字符串存入数据库中
        //添加到数据库
        db('vote_data')->insert(array('uid' => $this->uid, 'username' => $this->username, 'subjectid' => $subjectid, 'time' => $time, 'ip' => $this->ip, 'data' => $new_data));
        //查询投票奖励点数，并更新会员点数
        //更新投票人数
        db('vote_subject')->update(array('votenumber' => '+=1'), array('subjectid' => $subjectid));
        showmsg(L('vote_votesucceed'), "/vote/index/result/?subjectid=$subjectid&siteid=$siteid");
    }

    /**
     *
     * 投票结果显示
     */
    public function result() {
        $subjectid = abs(intval($_GET['subjectid']));
        //取出投票标题
        $subject_arr = db('vote_subject')->where(['subjectid' => $subjectid])->find();
        //获取投票选项
        $options = vote_option_model::get_options($subjectid);
        //新建一数组用来存新组合数据
        $total = 0;
        $vote_data = array();
        $vote_data['total'] = 0; //所有投票选项总数
        $vote_data['votes'] = 0; //投票人数
        //获取投票结果信息
        $infos = db('vote_data')->where(['subjectid' => $subjectid])->select();
        //循环每个会员的投票记录
        foreach ($infos as $subjectid_arr) {
            extract($subjectid_arr);
            $arr = string2array($data);
            foreach ($arr as $key => $values) {
                $vote_data[$key] += 1;
            }
            $total += array_sum($arr);
            $vote_data['votes'] ++;
        }
        $vote_data['total'] = $total;

        $vote_options = array();
        foreach ($options as $option) {
            if ($vote_data['total'] == 0) {
                $option['per'] = 0;
            } else {
                $option['per'] = intval($vote_data[$option['optionid']] / $vote_data['total'] * 100);
            }
            $option['num'] = $vote_data[$option['optionid']] == '' ? '0' : $vote_data[$option['optionid']];
            $vote_options[] = $option;
        }

        $this->assign('vote_subject', $subject_arr);
        $this->assign('vote_data', $vote_data);
        $this->assign('vote_options', $vote_options);
        $this->display('vote/vote_result', 'home');
    }

    /**
     *
     * 投票前检测
     * @param $subjectid 投票ID
     * @return 返回值 (1:可投票  0: 多投,时间段内不可投票  -1:单投,已投票,不可重复投票)
     */
    public function check($subjectid) {
        $siteid = $this->siteid;
        $subject_arr = db('vote_subject')->where(['subjectid' => $subjectid])->find();
        if ($subject_arr['enabled'] == 0) {
            showmsg(L('vote_votelocked'), "/vote/index/result/?subjectid=$subjectid&siteid=$siteid");
        }
        if (date("Y-m-d", TIMESTAMP) > $subject_arr['todate']) {
            showmsg(L('vote_votepassed'), "/vote/index/result/?subjectid=$subjectid&siteid=$siteid");
        }
        //游客是否可以投票
        if ($subject_arr['allowguest'] == 0) {
            if (!$this->username) {
                showmsg(L('vote_votenoguest'), "/vote/index/result/?subjectid=$subjectid&siteid=$siteid");
            } elseif ($this->groupid == '7') {
                showmsg('对不起，不允许邮件待验证用户投票！', "/vote/index/result/?subjectid=$subjectid&siteid=$siteid");
            }
        }
        //是否有投票记录
        $user_info = db('vote_data')->where(array('subjectid' => $subjectid, 'ip' => $this->ip, 'username' => $this->username))->select();
        if (!$user_info) {
            return 1;
        } else {
            if ($subject_arr['interval'] == 0) {
                return -1;
            }
            if ($subject_arr['interval'] > 0) {
                $condition = (TIMESTAMP - $user_info[0]['time']) / (24 * 3600) > $subject_arr['interval'] ? 1 : 0;
                return $condition;
            }
        }
    }

}
